package com.fh.config.security;

import com.fh.config.SecurityBeanUtils;
import com.fh.service.UserRepositoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration
@EnableWebSecurity
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)


public class CustomWebSecurityConfigurerAdapterConfig extends WebSecurityConfigurerAdapter {


    private final UserRepositoryService userRepository;

    private final SecurityBeanUtils beanUtils;

    public CustomWebSecurityConfigurerAdapterConfig(UserRepositoryService userRepository, SecurityBeanUtils beanUtils) {
        this.userRepository = userRepository;
        this.beanUtils = beanUtils;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/doc.html")
                .authenticated() // 需要认证的路径
                .anyRequest()
                .permitAll() // 其他所有请求允许访问
                .and()
                .formLogin()
                .loginPage("/login.html") // 指定登录页面的路径
                .loginProcessingUrl("/login") // 表单提交的处理路径
                .defaultSuccessUrl("/doc.html", true) // 登录成功后重定向的路径
                .failureHandler(beanUtils.customAuthenticationFailureHandler())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(beanUtils.authenticationEntryPoint())
                .accessDeniedHandler(beanUtils.accessDeniedHandler())
                .and()
                .csrf()
                .disable(); // 禁用 CSRF 攻击防护，方便测试
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        // 在内存中定义用户，用户名是user，密码是password，角色是USER
        auth.authenticationProvider(beanUtils.authenticationProvider());
        /*auth.userDetailsService(userDetailsService());*/
    }

    /*@Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            log.info("[USERNAME:]: {}", username);
            User user = userRepository.findByUsername(username);
            if(ObjectUtils.isEmpty(user)){
                throw new RuntimeException("账号密码错误");
            }
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

            if(user.isAccount(user.getAccountExpired())){
                throw new AuthenticationServiceException("账户已过期");
            }
            if(user.isAccount(user.getAccountLocked())){
                throw new AuthenticationServiceException("用户已禁用");
            }
            return org.springframework.security.core.userdetails.User.builder()
                    .username(user.getUsername())
                    .password(passwordEncoder.encode(user.getPassword()))
                    .authorities(new SimpleGrantedAuthority(user.getRole()))
                    .disabled(user.isAccount(user.getAccountLocked()))
                    .accountExpired(user.isAccount(user.getAccountExpired()))
                    .build();
        };
    }*/





}
